<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRentalStore, type RentalOrder } from '@/stores/rental'
import { ElMessage } from 'element-plus'

const rentalStore = useRentalStore()

const searchKeyword = ref('')
const statusFilter = ref('')
const filteredRentals = ref<RentalOrder[]>([])
const detailDialogVisible = ref(false)
const selectedOrder = ref<RentalOrder | null>(null)

onMounted(async () => {
  try {
    await rentalStore.fetchRentalList()
    filteredRentals.value = rentalStore.rentalList
  } catch (error) {
    ElMessage.error('加载租赁记录失败')
  }
})

const searchRentals = () => {
  let result = rentalStore.rentalList
  
  if (searchKeyword.value.trim()) {
    result = result.filter(rental => 
      rental.orderNo.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  if (statusFilter.value) {
    result = result.filter(rental => rental.status === statusFilter.value)
  }
  
  filteredRentals.value = result
}

const approveOrder = async (order: RentalOrder) => {
  try {
    await rentalStore.approveOrder(order.id)
    ElMessage.success('订单审批成功，已转为租赁中状态')
    await rentalStore.fetchRentalList()
    filteredRentals.value = rentalStore.rentalList
    searchRentals()
  } catch (error) {
    ElMessage.error('订单审批失败')
  }
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'PENDING': return 'warning'
    case 'ACTIVE': return 'primary'
    case 'COMPLETED': return 'success'
    case 'CANCELLED': return 'danger'
    case 'OVERDUE': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'PENDING': return '待处理'
    case 'ACTIVE': return '租赁中'
    case 'COMPLETED': return '已完成'
    case 'CANCELLED': return '已取消'
    case 'OVERDUE': return '逾期'
    default: return '未知'
  }
}

const processReturn = async (order: RentalOrder) => {
  try {
    await rentalStore.returnEquipment(order.id)
    ElMessage.success('设备归还处理成功')
    await rentalStore.fetchRentalList()
    filteredRentals.value = rentalStore.rentalList
    searchRentals()
  } catch (error) {
    ElMessage.error('处理归还失败')
  }
}

const showOrderDetail = (order: RentalOrder) => {
  selectedOrder.value = order
  detailDialogVisible.value = true
}
</script>

<template>
  <div class="rental-records">
    <div class="page-header">
      <h1>租赁记录</h1>
      <div class="header-actions">
        <el-select
          v-model="statusFilter"
          placeholder="筛选状态"
          clearable
          style="width: 150px; margin-right: 16px"
          @change="searchRentals"
        >
          <el-option label="待处理" value="PENDING" />
          <el-option label="租赁中" value="ACTIVE" />
          <el-option label="已完成" value="COMPLETED" />
          <el-option label="已取消" value="CANCELLED" />
          <el-option label="逾期" value="OVERDUE" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索订单号"
          style="width: 300px"
          @input="searchRentals"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <el-card>
      <el-table :data="filteredRentals" stripe>
        <el-table-column prop="orderNo" label="订单号" width="150" />
        <el-table-column prop="userId" label="用户ID" width="80" />
        <el-table-column prop="equipmentId" label="设备ID" width="80" />
        <el-table-column prop="rentalStartDate" label="开始日期" width="120" />
        <el-table-column prop="rentalEndDate" label="结束日期" width="120" />
        <el-table-column prop="plannedReturnDate" label="计划归还" width="120" />
        <el-table-column prop="actualReturnDate" label="实际归还" width="120">
          <template #default="{ row }">
            {{ row.actualReturnDate || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="dailyRentPrice" label="日租金" width="100">
          <template #default="{ row }">
            ¥{{ row.dailyRentPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="100">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 'PENDING'" 
              type="success" 
              size="small"
              @click="approveOrder(row)"
            >
              审批通过
            </el-button>
            <el-button 
              v-if="row.status === 'ACTIVE'" 
              type="primary" 
              size="small"
              @click="processReturn(row)"
            >
              处理归还
            </el-button>
            <el-button size="small" @click="showOrderDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="600px">
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ selectedOrder.userId }}</el-descriptions-item>
          <el-descriptions-item label="设备ID">{{ selectedOrder.equipmentId }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ selectedOrder.rentalStartDate }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ selectedOrder.rentalEndDate }}</el-descriptions-item>
          <el-descriptions-item label="计划归还日期">{{ selectedOrder.plannedReturnDate }}</el-descriptions-item>
          <el-descriptions-item label="实际归还日期">{{ selectedOrder.actualReturnDate || '暂未归还' }}</el-descriptions-item>
          <el-descriptions-item label="日租金">¥{{ selectedOrder.dailyRentPrice }}</el-descriptions-item>
          <el-descriptions-item label="押金">¥{{ selectedOrder.depositAmount }}</el-descriptions-item>
          <el-descriptions-item label="总金额">¥{{ selectedOrder.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusColor(selectedOrder.status)">
              {{ getStatusText(selectedOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ selectedOrder.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">{{ selectedOrder.updatedAt }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ selectedOrder.notes || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          v-if="selectedOrder && selectedOrder.status === 'PENDING'" 
          type="success"
          @click="approveOrder(selectedOrder)"
        >
          审批通过
        </el-button>
        <el-button 
          v-if="selectedOrder && selectedOrder.status === 'ACTIVE'" 
          type="primary"
          @click="processReturn(selectedOrder)"
        >
          处理归还
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.rental-records {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}
</style>